
#fastlane_version "2.205.1"
fastlane_require 'dotenv'
default_platform(:ios)

is_ci = true

FIR_TOKEN = '329d0a0f867c11d9a81b9577c80d7b5b'

build_provision = "/Users/p88health/profiles/fastlane/Distribution/ios_production_2021.mobileprovision"
build_ex_provision = "/Users/p88health/profiles/fastlane/Distribution/ios_production_shareEx_2021.mobileprovision"

pgyer_build_provision = "/Users/p88health/profiles/fastlane/Distribution/ios_adhoc_2021.mobileprovision"
pgyer_build_ex_provision = "/Users/p88health/profiles/fastlane/Distribution/ios_adhoc_shareEx_2021.mobileprovision"


platform :ios do

  lane :prepare_certificates do |options|
    create_keychain(
      name: "default_keychain",
      default_keychain: true,
      unlock: true,
      password: "Pier88health"
    )
    import_certificate(
      certificate_path: "/Users/p88health/profiles/fastlane/Distribution/2021_08p12Certificates.p12",
      certificate_password: "123456",
      keychain_name: "default_keychain",
      keychain_password: "Pier88health"
    )
    unlock_keychain(path:"default_keychain", password:"Pier88health")
    sh "security set-keychain-settings -t 3600 -l ~/Library/Keychains/default_keychain-db"
  end


  def import_ios_certificate(filename)
    puts  'runnnn pre cert function------->'
    puts  "/Users/p88health/profiles/fastlane/developer/#{filename}.p12"
    sh "security -v unlock-keychain -p Pier88health ~/Library/Keychains/login.keychain-db"
    import_certificate(
      certificate_path: "/Users/p88health/profiles/fastlane/developer/#{filename}.p12",
      certificate_password: "123456",
      keychain_name: "login.keychain-db",
      keychain_password: "Pier88health"
    )
    unlock_keychain(path:"login.keychain-db", password:"Pier88health")
    sh "security set-keychain-settings -t 3600 -l ~/Library/Keychains/login.keychain-db"
  end


  desc "Creating a code signing certificate and provisioning profile"
  # 任务名称
  lane :provision do
    # 创建 ITC 中的 App 信息
    produce(
      app_name: '彼爱医疗-测试',
      language: 'zh-Hans',
      app_version: '1.0',
      sku: 'com.pier88health.com.qa'
    )
    # 使用证书创建私钥及签名
    cert
    # 每次运行时创建新的配置文件
    sigh(force: true)

  end

  desc "Push a new dev build"
  lane :dev do
    Dir.chdir('..') do
        sh("cp ../.env /tmp/envfile")
        sh('less "/tmp/envfile"')
    end
    Dotenv.load("../../.env")

    others_pre_setup('Nerivio-dev')

    if is_ci
      puts "Unlocking the keychain..."
      import_ios_certificate('Iphone_developer_W4K4RJC99D_11_21_2020_Certificates')
    end
#     if is_ci
#       puts "Disabling prompts for codesign..."
#       sh "security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k Pier88health login.keychain-db"
#     end


    gym(
      clean: true,
      # 使用.env配置的环境变量
      scheme:  ENV['Scheme'],
      # app-store, ad-hoc, package, enterprise, development, developer-id
      export_method: "development",
      include_bitcode: false,
      # skip_profile_detection: true,
      # export_xcargs: "-allowProvisioningUpdates",
      export_options: {
        # compileBitcode: false,
        # signingStyle: "manual",
        provisioningProfiles: {
            ENV['App_Identifier'] => "Nerivio_Dev",
        }
      },
      output_name: "#{ENV['Scheme']}.ipa",
      configuration: "Debug",
      # 输出日志的目录
      #buildlog_path: "fastlanelog",
      # 输出编译结果
      output_directory: "../bundle/ios/ipa",
      #include_bitcode: false
    )
    APK_LOCATION = "#{lane_context[SharedValues::IPA_OUTPUT_PATH]}"
    uploadToFir(APK_LOCATION)
  end



  desc "Push a new beta build to TestFlight"
  lane :beta do

    Dir.chdir('..') do
      sh("cp ../.env.qa /tmp/envfile")
      sh('less "/tmp/envfile"')
    end
    Dotenv.load("../../.env.qa")

    others_pre_setup('Nerivio-qa')

    if is_ci
      puts "Unlocking the keychain..."
      import_ios_certificate('Iphone_developer_W4K4RJC99D_11_21_2020_Certificates')
    end
    #
    #
#     if is_ci
#       puts "Disabling prompts for codesign..."
#       sh "security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k Pier88health login.keychain-db"
#     end

    gym(
      # 使用.env配置的环境变量
      scheme:  ENV['Scheme'],
      export_method: "development",
      export_options: {
        provisioningProfiles: {
            ENV['App_Identifier'] => "Nerivio_Qa",
        }
      },
      clean: true,
      output_name: "#{ENV['Scheme']}.ipa",
      configuration: "AdHoc",
      # 输出日志的目录
      #buildlog_path: "fastlanelog",
      # 输出编译结果
      output_directory: "../bundle/ios/ipa",
      #include_bitcode: false
    )

    APK_LOCATION = "#{lane_context[SharedValues::IPA_OUTPUT_PATH]}"
    uploadToFir(APK_LOCATION)
  end



  desc "Push a new staging build to TestFlight"
  lane :staging do

    Dir.chdir('..') do
      sh("cp ../.env.staging /tmp/envfile")
      sh('less "/tmp/envfile"')
    end
    Dotenv.load("../../.env.staging")
    others_pre_setup('Nerivio-staging')
    if is_ci
      puts "Unlocking the keychain..."
      import_ios_certificate('Iphone_developer_W4K4RJC99D_11_21_2020_Certificates')
    end
#     if is_ci
#       puts "Disabling prompts for codesign..."
#       sh "security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k Pier88health login.keychain-db"
#     end

    gym(
      # 使用.env配置的环境变量
      scheme:  ENV['Scheme'],
      # app-store, ad-hoc, package, enterprise, development, developer-id
      export_method: "development",
      # export_xcargs: "-allowProvisioningUpdates",
      export_options: {
        provisioningProfiles: {
            ENV['App_Identifier'] => "Nerivio_Staging",
        }
      },
      clean: true,
      output_name: "#{ENV['Scheme']}.ipa",
      configuration: "Staging",
      # 输出日志的目录
      #buildlog_path: "fastlanelog",
      # 输出编译结果
      output_directory: "../bundle/ios/ipa",
      #include_bitcode: false
    )
    #firim(firim_api_token: ENV['FIR_TOKEN'], app_changelog: "#{git_branch}-#{last_git_commit[:author]}-#{last_git_commit[:abbreviated_commit_hash]}-#{last_git_commit[:message]}")

    APK_LOCATION = "#{lane_context[SharedValues::IPA_OUTPUT_PATH]}"
    uploadToFir(APK_LOCATION)
  end

  desc "change_pgyer_provisioning"
  lane :change_pgyer_provisioning do
    puts pgyer_build_provision
    UI.message "Setting provisioning profile"

    update_project_provisioning(
      xcodeproj: "Nerivio.xcodeproj",
      profile: pgyer_build_provision, # optional if you use sigh
      target_filter: "Nerivio", # matches name or type of a target
      build_configuration: "Release",
      # code_signing_identity: "iPhone Distribution: PIER 88 HEALTH, INC. (28W58M8G88)" # optionally specify the codesigning identity
    )
    update_project_provisioning(
      xcodeproj: "Nerivio.xcodeproj",
      profile: pgyer_build_ex_provision, # optional if you use sigh
      target_filter: "NerivioEx", # matches name or type of a target
      build_configuration: "Release",
      # code_signing_identity: "iPhone Distribution: PIER 88 HEALTH, INC. (28W58M8G88)" # optionally specify the codesigning identity
    )
  end

  desc "Push a new prod build to pgyer production"
  lane :pgyer_prod do
    change_pgyer_provisioning()
    puts pgyer_build_provision

    prod_pre_setup('Nerivio')
    # set_prod_key_cert()

    adhocProdName = "pgyerprod_#{ENV['Scheme']}_#{Time.now.strftime('%Y%m%d%H%M%S')}.ipa"
    gym(
      # 使用.env配置的环境变量
      scheme:  ENV['Scheme'],
      # app-store, ad-hoc, package, enterprise, development, developer-id
      export_method: "ad-hoc",
      # export_options: {
      #   provisioningProfiles: {
      #       ENV['App_Identifier'] => "Production_AdHoc_Debug_Provisiong",
      #       ENV['App_Share_Identifier'] => "Production_AdHoc_Debug_ShareEx"
      #   }
      # },
      clean: true,
      output_name: adhocProdName,
      configuration: "Release",
      # 输出日志的目录
      #buildlog_path: "fastlanelog",
      # 输出编译结果
      output_directory: "../bundle/ios/ipa",
      #include_bitcode: false
    )

    APK_LOCATION = "#{lane_context[SharedValues::IPA_OUTPUT_PATH]}"
    uploadToFir(APK_LOCATION)
  end

  # fastlane spaceauth -u app@pier88health.com
  desc "Push a new prod build to apple store"
  lane :appstore_prod do

    increment_build_number(xcodeproj: "Nerivio.xcodeproj")
    commit_version_bump(xcodeproj: "Nerivio.xcodeproj", message: 'Version Bump by fastlane', force: true)

    prod_pre_setup('Nerivio')
    puts "Start to build ....."

    UI.message "Setting provisioning profile"

    appstore_ipa_name = "applestore_#{ENV['Scheme']}_#{Time.now.strftime('%Y%m%d%H%M%S')}.ipa"
    puts ' ======== IPA NAME ======'
    puts appstore_ipa_name
    puts ' ======== IPA NAME ======'
    gym(
      # 使用.env配置的环境变量
      scheme:  ENV['Scheme'],
      # app-store, ad-hoc, package, enterprise, development, developer-id
      export_method: "app-store",
      # export_options: {
      #   provisioningProfiles: {
      #       ENV['App_Identifier'] => "Production_AppStore_Provisiong",
      #       ENV['App_Share_Identifier'] => "Production_AppStore_ShareEx_Provisiong"
      #   }
      # },
      clean: true,
      output_name: appstore_ipa_name,
      configuration: "Release",
      include_bitcode: true,
      include_symbols: true,
      export_xcargs: "-allowProvisioningUpdates",
      # compileBitcode: false,
      # 输出日志的目录
      #buildlog_path: "fastlanelog",
      # 输出编译结果
      output_directory: "../bundle/ios/ipa",
      archive_path:  "../bundle/ios/build.xcarchive",
      #include_bitcode: false
    )



    ENV["FASTLANE_USER"] = "app@pier88health.com"
    ENV["FASTLANE_PASSWORD"] = "Pier88health"
    ENV['FASTLANE_APPLE_APPLICATION_SPECIFIC_PASSWORD'] = "dabj-wtho-dgtz-mnax"
    puts ENV["FASTLANE_PASSWORD"]
    puts "======== Start to update appstore ========"
    # update_app_store()
    deliver(
      skip_binary_upload: false,
      skip_screenshots: true,
      skip_metadata: false,
      metadata_path: "./fastlane/metadata",
      #screenshots_path: "./fastlane/screenshots",
      force: true,
      submit_for_review: true,
      automatic_release: true,
      ipa: "../bundle/ios/ipa/#{appstore_ipa_name}"
    )
    puts "======== end to update appstore ========"
  end

  def others_pre_setup(project)
    puts "Pre Setup....."
    puts project
    version = get_version_number(
      xcodeproj: "Nerivio.xcodeproj",
      target: "Nerivio"
    )
    ENV["DELIVER_PACKAGE_VERSION"] = version
    ENV["DELIVER_PROJECT_NAME"] = project
    ENV["DELIVER_COMMIT"]  = Time.new.strftime("%a-%d-%b-%Y-%H:%M:%S-+0000")
    # ENV["DELIVER_PROJECT_ID"] = appid
    Dir.chdir('../../') do
        sh('sed "6 s/--project.*upload-sourcemaps/--project ''$DELIVER_PROJECT_NAME'' files $App_Identifier-$DELIVER_PACKAGE_VERSION upload-sourcemaps/g" package.json > package.json.tmp && mv package.json.tmp package.json')
        sh('sed -n 6p package.json')
    end
    Dir.chdir('..') do
#         sh('sed "3 s/defaults.project=Nerivio.*/defaults.project=$DELIVER_PROJECT_NAME/g" sentry.properties > sentry.properties.tmp && mv sentry.properties.tmp sentry.properties')
        sh('less sentry.properties')
    end
    puts "Pre Setup End....."
  end

  def others_end_setup()
    # Dir.chdir('..') do
    #     sh('sed "3 s/defaults.project=Nerivio.*/defaults.project=Nerivio-dev/" sentry.properties > sentry.properties.tmp && mv sentry.properties.tmp sentry.properties')
    #     sh('less sentry.properties')
    # end
    # Dir.chdir('../../') do
    #     sh('sed "7 s/--project.*/--project\",/g" package.json > package.json.tmp && mv package.json.tmp package.json')
    #     sh('sed -n 7p package.json')
    # end
  end


  def prod_pre_setup(project)
    Dir.chdir('..') do
        sh("cp ../.env.production /tmp/envfile")
        sh('less "/tmp/envfile"')
    end
    Dotenv.load("../../.env.production")

    version = get_version_number(
      xcodeproj: "Nerivio.xcodeproj",
      target: "Nerivio"
    )
    ENV["DELIVER_PROJECT_NAME"] = project
    ENV["DELIVER_PACKAGE_VERSION"] = version
    ENV["DELIVER_COMMIT"]  = Time.new.strftime("%a-%d-%b-%Y-%H:%M:%S-+0000")
    Dir.chdir('../../') do
        #sh('sed "6 s/--project.*upload-sourcemaps/--project ''$DELIVER_PROJECT_NAME'' files $App_Identifier-$DELIVER_PACKAGE_VERSION set-commits ''$DELIVER_PACKAGE_VERSION'' --commit ''$DELIVER_PROJECT_NAME-$DELIVER_COMMIT'' upload-sourcemaps/g" package.json > package.json.tmp && mv package.json.tmp package.json')
        sh('sed "6 s/--project.*upload-sourcemaps/--project ''$DELIVER_PROJECT_NAME'' files $App_Identifier-$DELIVER_PACKAGE_VERSION upload-sourcemaps/g" package.json > package.json.tmp && mv package.json.tmp package.json')
        sh('sed -n 6p package.json')
    end

    Dir.chdir('..') do
#         sh('sed "3 s/defaults.project=Nerivio.*/defaults.project=Nerivio/" sentry.properties > sentry.properties.tmp && mv sentry.properties.tmp sentry.properties')
#         sh('less sentry.properties')
    end

  end

  lane :set_prod_key_cert do
    if is_ci
      puts "Unlocking the keychain..."
      import_ios_certificate('2021_08p12Certificates')
    end

    sh('pwd')
    #
    #
    if is_ci
      puts "Disabling prompts for codesign..."
      sh "security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k Pier88health login.keychain-db"
    end
  end

  lane :update_app_store do
    puts "======== increment number ========"
    # increment_build_number
    # 编译代码
    puts "======== gem build ========"
    # gym(
    #     scheme:"Nerivio",
    #     export_method:"app-store",
    #     )
    # 发布到 Apple Store

    deliver(
      ipa: "../bundle/ios/applestore_Nerivio_20190601111031.ipa",
      metadata_path: "./fastlane/metadata",
      submit_for_review: true,
      force: true
    )
    # deliver
  end

  def uploadToFir(appName)
    ENV["APP_BUILD_NAME"] = appName
    ENV["APP_COMMIT"] = "#{git_branch}-#{last_git_commit[:author]}-#{last_git_commit[:abbreviated_commit_hash]}-#{last_git_commit[:message]}"
    sh("fir login #{FIR_TOKEN}")
    sh('fir me')
    sh('fir publish ''$APP_BUILD_NAME'' -c=''$APP_COMMIT''')
  end

  def update_app_identifier(app_id)
    update_info_plist(
        xcodeproj:PROJECT_FILE_PATH ,
        app_identifier:app_id,
        plist_path:"#{PLIST_FILE_PATH}"
    )
    update_info_plist(
        xcodeproj:PROJECT_FILE_PATH ,
        app_identifier:app_id,
        plist_path:"#{UNITTEST_PLIST_FILE_PATH}"
    )
  end


  after_all do |lane|
      puts "Successfully deployed new App Update."
   end

   error do |lane, exception|
      puts exception.message
   end

end
